<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :md="8" :sm="12">
            <a-form-item label="日期">
              <a-range-picker
                :mode="['date', 'date']"
                :placeholder="['开始月份', '结束月份']"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                style="width: 100%;"
                :disabled-date="disabledDate"
                :value="queryParam.time"
                @change="panelChange"
              />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExport">导出</a-button>
    </div>
    <a-tabs v-model="activeKey" @change="callback">
      <a-tab-pane v-for="item in tabList" :tab="item.tab" :key="item.key">
        <a-table
          ref="table"
          bordered
          :scroll="{x:true}"
          :components="draggableComponent(columns)"
          size="middle"
          rowKey="key"
          :columns="columns"
          :dataSource="item.dataSource"
          :pagination="pagination"
          @change="pageChange"
          :loading="loading"
        >
          <template slot="processName" slot-scope="text, record">
            <a @click="showModal(record)">{{ text }}</a>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <processTaskModal ref="processTaskModal"></processTaskModal>
  </a-card>
</template>

<script>
import moment from 'dayjs'
import { defColumns } from './average.js'
import processTaskModal from '../modules/processTaskModal.vue'
import { downFile, getAction } from '@/api/manage'
export default {
  name: 'Average',
  components: {
    processTaskModal
  },
  data() {
    return {
      loading: false,
      activeKey: 'administration',
      url: {
        exportXlsUrl: '/api/erp/hr/apply/erpHrApplyRegisterBill/exportXls',
        importExcelUrl: 'api/erp/hr/apply/erpHrApplyRegisterBill/importExcel'
      },
      queryParam: {
        time: []
      },
      columns: [],
      tabList: [
        { key: 'administration', tab: '行政管理', columns: defColumns.administration, dataSource: [] },
        // { key:'oa', tab:'OA办公', columns: defColumns.oa, dataSource:[] },
        { key: 'hr', tab: '人事管理', columns: defColumns.hr, dataSource: [] },
        { key: 'finance', tab: '财务管理', columns: defColumns.finance, dataSource: [] },
        // { key:'business', tab:'业务办理', columns: defColumns.business, dataSource:[] },
        { key: 'omc', tab: '项目管理', columns: defColumns.omc, dataSource: [] },
        { key: 'purchase', tab: '招采管理', columns: defColumns.purchase, dataSource: [] },
        { key: 'contract', tab: '合同管理', columns: defColumns.contract, dataSource: [] },
        { key: 'audit', tab: '审计管理', columns: defColumns.audit, dataSource: [] }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  created() {
    // 获取columns
    this.queryParam.time = [moment(new Date()).startOf('month').format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')]
    this.loadColumns()
    this.loadData('administration')
  },
  methods: {
    draggableComponent: function(columns) {
      return this.dragResizable(columns)
    },
    showModal(record) {
      let value = Object.assign({}, record)
      value.processKey = record.process_key
      value.startDate = this.queryParam.time[0]
      value.endDate = this.queryParam.time[1]
      value.sortType = 'consumeTime'
      this.$refs.processTaskModal.showModal(value)
    },
    disabledDate(current) {
      // 禁用选择时间大于今天
      // return current && current > moment().subtract(0, 'days').endOf('day') 与相面相同
      return current && current > moment().add(0, 'days').startOf('day')
    },
    searchQuery() {
      this.loadData(this.activeKey)
    },
    searchReset() {
      this.queryParam.time = [moment(new Date()).startOf('month').format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')]
      this.loadData(this.activeKey)
    },
    pageChange(val) {
      this.pagination = val
    },
    loadData(processType) {
      let startTime = this.queryParam.time[0]
      let endTime = this.queryParam.time[1]
      this.loading = true
      getAction('/api/erpmng/sys/board/taskDurationPerProcess', { processType, startTime, endTime }).then(res => {
        if (res.success) {
          let data = res.result.length ? res.result.map((val, index) => {
            val.key = index
            return val
          }) : []
          this.$set(this.tabList[this.tabList.findIndex(val => val.key == processType)], 'dataSource', data)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    loadColumns () {
      var params = {
        processType: this.activeKey,
        startTime: this.queryParam.time[0],
        endTime: this.queryParam.time[1]
      }
      getAction('/api/erpmng/sys/board/nodeNameMap', params).then(res => {
        if (res.success) {
          // 处理res.result中为width和ellipsis值
          if (res.result && res.result.length > 0) {
            this.columns = res.result.map(val => {
              val.ellipsis = true
              val.width = 200
              return val
            })
            this.columns.unshift(
              {
                title: '序号',
                align: 'center',
                key: 'rowIndex',
                width: 60,
                ellipsis: true,
                customRender: function (t, r, index) {
                  return parseInt(index) + 1;
                }
              },
              {
                title: '表单名称',
                ellipsis: true,
                align: 'center',
                width: 200,
                dataIndex: 'process_name',
                scopedSlots: { customRender: 'processName' },
              }
            )
          } else {
            this.columns = []
          }
        }
      })
    },
    callback(val) {
      this.pagination.current = 1
      this.activeKey = val
      this.columns = []
      this.loadColumns()
      this.loadData(val)
    },
    panelChange(value) {
      this.queryParam.time = value
    },
    handleExport() {
      let fileName = this.tabList[this.tabList.findIndex(val => val.key == this.activeKey)].tab
      let param = {};
      let startTime = this.queryParam.time[0]
      let endTime = this.queryParam.time[1]
      param.startTime = startTime
      param.endTime = endTime
      param.processType = this.activeKey
      downFile('/api/erpmng/sys/board/exportTaskDurationPerProcess', param).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            }),
            fileName + '.xls'
          )
        } else {
          let url = window.URL.createObjectURL(
            new Blob([data], {
              type: 'application/vnd.ms-excel'
            })
          )
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    }
  }
}
</script>
<style scoped></style>
